package ez

import (
	"beergo/conf/const/code"
	model "beergo/app/sys/documents"
	"beergo/lib/base/controller"
	"beergo/lib/base/reflect"
	"beergo/lib/event"
	mgo "beergo/lib/mongo"
	"beergo/lib/tool"
	"encoding/json"
	"github.com/beego/beego/v2/core/config"
	"strings"
	"beergo/app/sys/conf/preload"
)


type ErrorLogMongoDbController struct {
	controller.ContainerController
	QueryBuilder *mgo.QueryBuilder
	Repository   model.ErrorLogRepository
	Config       config.Configer
	Model        *model.ErrorLog
	JsonData     map[string]interface{}
}

func (this *ErrorLogMongoDbController) Prepare() {
	this.Config = preload.ErrorLogConfig
	this.JsonData = make(map[string]interface{})
	this.Repository = model.ErrorLogRepository{}
	this.Model = &model.ErrorLog{}
	qb := new(mgo.QueryBuilder)
	this.QueryBuilder = qb.CreateFromRequest(this.Ctx).SetEntityName("ErrorLog").SetConfig(this.Config)
	ae := &event.AuthEvent{
		Name:    "ErrorLogAuth",
		Access:  true,
		Message: "",
	}
	event.DispatchToManySync("ErrorLogAuth", ae, this.Ctx)
	if ae.Access == false {
		this.StopError(code.ErrorAccess, ae.Message, "")
	}
}

func (this *ErrorLogMongoDbController) ListAction() {
	lists, err := this.Repository.GetList(this.QueryBuilder)
	if err != nil {
		this.StopError(code.Error, "系统错误", err.Error())
	}
	this.JsonData["lists"] = lists
	this.JsonData["query"] = this.QueryBuilder.FeedBack()
	this.ReturnSuccess("OK", this.JsonData)
}

func (this *ErrorLogMongoDbController) GetAction() {
	id := this.GetString(":id")
	data := this.Repository.Find(id)
	this.ReturnSuccess("OK.", data)
}

func (this *ErrorLogMongoDbController) CreateAction() {
	entity := this.Model.New()
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &entity)
	this.AnaliseErrors(err)
	errSave := entity.Save()
	this.AnaliseErrors(errSave)
	this.ReturnSuccess("OK", "")
}

func (this *ErrorLogMongoDbController) UpdateAction() {
	id := this.GetParamString("id")
	entity := this.Repository.Find(id)
	fields := this.GetBodyParamAll()
	err := entity.Save(fields)
	this.AnaliseErrors(err)
	this.ReturnSuccess("OK", entity.Id.String())
}

func (this *ErrorLogMongoDbController) PutAction() {
	entity := this.Model
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &entity)
	this.AnaliseErrors(err)
	errSave := entity.Save()
	this.AnaliseErrors(errSave)
	this.ReturnSuccess("OK", entity.Id.String())
}

func (this *ErrorLogMongoDbController) CopyAction() {
	ids := this.GetParamStrings("ids")
	for _, id := range ids {
		entity := this.Repository.Find(id)
		newEntity := this.Model
		err := tool.Clone(entity, newEntity)
		this.AnaliseErrors(err)
		err = newEntity.Save()
		this.AnaliseErrors(err)
	}
	this.ReturnSuccess("OK", ids)
}

func (this *ErrorLogMongoDbController) DeleteAction() {
	ids := this.GetParamStrings("ids")
	for _, id := range ids {
		entity := this.Repository.Find(id)
		err := entity.Delete()
		this.AnaliseErrors(err)
	}
	this.ReturnSuccess("OK", "")
}

func (this *ErrorLogMongoDbController) ChoiceAction() {
	//字段准备
	fieldsStr := this.GetParamString("fields")
	fields := strings.Split(fieldsStr, ",")
	hasNull := this.GetParamBool("hasNull")
	labelName := this.GetParamString("label")
	valueName := this.GetParamString("value")
	if labelName == "" {
		labelName = "value"
	}
	if valueName == "" {
		valueName = "id"
	}
	//列表数据获取
	listQuery := new(controller.ListQuery)
	this.IgnoreErrors(this.FillModel(listQuery))
	data := this.Repository.FindBy(listQuery.CreateFilter(), listQuery.CreateOrder(), listQuery.CreateLimit(), listQuery.CreateOffset())
	var choices []map[string]interface{}
	var offset int
	if hasNull {
		choices = make([]map[string]interface{}, len(data)+1)
		choices[0] = map[string]interface{}{valueName: "", labelName: "请选择"}
		offset = 1
	} else {
		choices = make([]map[string]interface{}, len(data))
		offset = 0
	}
	for index, datum := range data {
		value := ""
		for _, field := range fields {
			value += reflect.ValueOf(datum, field).String()
		}
		choices[index+offset] = map[string]interface{}{valueName: datum.Id, labelName: value}
	}
	this.JsonData["lists"] = choices
	this.JsonData["query"] = this.QueryBuilder.FeedBack()
	this.ReturnSuccess("OK", this.JsonData)
}
